let tableIns;
let tree;
layui.use(['element', 'form', 'layer'], function () {
    let form = layui.form;//select、单选、复选等依赖form
    let element = layui.element; //导航的hover效果、二级菜单等功能，需要依赖element模块
    
    $.post(ctx + '/seller/sellerlist/list', {}, function (data) {
        var $html = "";
        if(data.data != null){
            $.each(data.data, function (index, item) {
            	console.log(item);
            	if(item.agentName != null){
            		$html += "<option value='" + item.sellerId + "'>" + item.sellerName +'&nbsp;&nbsp;&nbsp;手机号:'+item.sellerMobile+'&nbsp;&nbsp;&nbsp;已关联:'+item.agentName+ "</option>";
            	}else{
            		$html += "<option value='" + item.sellerId + "'>" + item.sellerName +'&nbsp;&nbsp;&nbsp;手机号:'+item.sellerMobile+ '&nbsp;&nbsp;&nbsp;未关联'+"</option>";
            	}
            });
            $("select[name='sellerId']").append($html);
            form.render('select','sellerIdfilter');
        }
    });
    
    $.post(ctx + '/agent/agentlist/list', {}, function (data) {
        var $html = "";
        if(data.data != null){
            $.each(data.data, function (index, item) {
            	$html += "<option value='" + item.agentId + "'>" + item.agentName +'&nbsp;&nbsp;&nbsp;手机号:'+item.agentPhone+ "</option>";
            });
            $("select[name='agentId']").append($html);
            form.render('select','agentIdfilter');
        }
    });
    
    $(function(){
       //输入框的值改变时触发
      $("input[name='baseAmountPoint']").on("input",function(e){
        var val = $("input[name='serverAmountPoint']").val();
        $("input[name='overAmountPoint']").val(val - e.delegateTarget.value);
      });
    });
    
});

/**
 * 提交保存
 */
function refFormSave() {
    let refForm = $("#refForm").serializeObject();
    let sellerId = refForm.sellerId;
    if(sellerId == '-1'){
        layer.msg('请选取商户',{icon: 6});
        return false;
    }
    let agentId = refForm.agentId;
    if(agentId == '-1'){
        layer.msg('请选取代理商',{icon: 6});
        return false;
    }

    var reg = /^[0-9]{1,2}(\.[0-9]{0,2})?$/
    if( null != refForm.serverAmountPoint && !reg.test(refForm.serverAmountPoint) ){
        layer.msg('签约点数输入不正确，格式为：x.x',{icon: 5});
        return false;
    }
    
    save();
}

function save(){
	let refForm = $("#refForm").serializeObject();
    $.post(ctx + "/seller/ref/saveRef", refForm, function (data) {
        if(data == null){
            layer.msg("访问接口出现异常!", {icon: 5});
        }else if(data.flag){
	        layer.msg("新增成功", {icon: 1, time: 2000}, function(){
	        	var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
	        	parent.layer.close(index); //再执行关闭
	        	window.parent.$("#queryBySellerNameBtn").click();
	        });
    	} else {
    		layer.msg("该商户已经绑定了代理商，无法重复绑定或无法绑定多个代理商!", {icon: 5});
    	}
    });
}